<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

// 接口定义
interface Customer {
  id: string;
  name: string;
  petName: string;
  phone: string;
  memberLevel: 'gold' | 'normal';
  memberCard: string;
  balance: number;
  type: 'registered' | 'walkin';
}

interface Product {
  id: string;
  name: string;
  specification: string;
  unit: string;
  unitPrice: number;
  discountEligible: boolean;
  quantity: number;
  total: number;
  salesPerson: string;
  servicePerson: string;
}

interface Props {
  visible: boolean;
  amount: number;
  customer: Customer | null;
  products: Product[];
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const deposit = ref<number>(50);
const discountType = ref<'member' | 'none' | 'whole'>('member');
const wholeOrderDiscount = ref<number>(10);
const manualDiscount = ref<number>(0);
const roundOff = ref<boolean>(false);
const roundOffAmount = ref<number>(0);

const paymentMethods = ref({
  alipay: false,
  wechat: false,
  cash: false,
  card: false,
  deposit: false,
});

const paymentAmounts = ref({
  alipay: 0,
  wechat: 0,
  cash: 0,
  card: 0,
  deposit: 0,
});

const useMemberCard = ref<boolean>(true);
const memberCardPayment = ref({
  balance: 0,
  gift: 0,
});

const remarks = ref<string>('');
const autoPrint = ref<boolean>(true);

// 计算属性
const discountAmount = computed(() => {
  switch (discountType.value) {
    case 'member': {
      return props.amount * 0.3; // 7折优惠
    }
    case 'none': {
      return manualDiscount.value;
    }
    case 'whole': {
      return wholeOrderDiscount.value;
    }
    // No default
  }
  return 0;
});

const finalAmount = computed(() => {
  return props.amount - discountAmount.value;
});

const earnedPoints = computed(() => {
  return Math.floor(finalAmount.value);
});

const totalPayment = computed(() => {
  let total = 0;

  // 其他支付方式
  Object.values(paymentAmounts.value).forEach((amount) => {
    total += amount;
  });

  // 会员卡支付
  if (useMemberCard.value) {
    total += memberCardPayment.value.balance + memberCardPayment.value.gift;
  }

  return total;
});

// 方法
const handleDiscountChange = () => {
  memberCardPayment.value.balance =
    discountType.value === 'member' ? finalAmount.value : 0;discountType.valuefinalAmount.valuediscountType.valuefinalAmount.value
};

const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};

const handleConfirm = () => {
  if (Math.abs(totalPayment.value - finalAmount.value) > 0.01) {
    message.warning('支付金额与应付金额不匹配');
    return;
  }

  if (
    useMemberCard.value &&
    memberCardPayment.value.balance > (props.customer?.balance || 0)
  ) {
    message.warning('会员卡余额不足');
    return;
  }

  // 模拟结算成功
  message.success('结算成功！');
  emit('success');
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  deposit.value = 50;
  discountType.value = 'member';
  wholeOrderDiscount.value = 10;
  manualDiscount.value = 0;
  roundOff.value = false;
  roundOffAmount.value = 0;

  Object.keys(paymentMethods.value).forEach((key) => {
    paymentMethods.value[key as keyof typeof paymentMethods.value] = false;
  });

  Object.keys(paymentAmounts.value).forEach((key) => {
    paymentAmounts.value[key as keyof typeof paymentAmounts.value] = 0;
  });

  useMemberCard.value = true;
  memberCardPayment.value = { balance: 0, gift: 0 };
  remarks.value = '';
  autoPrint.value = true;
};

// 监听最终金额变化，自动设置会员卡支付
watch(finalAmount, (newAmount) => {
  if (discountType.value === 'member' && useMemberCard.value) {
    memberCardPayment.value.balance = newAmount;
  }
});

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible && props.customer && discountType.value === 'member') {
      memberCardPayment.value.balance = finalAmount.value;
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="收银结算"
    width="600px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="settlement-modal">
      <!-- 订单和顾客信息 -->
      <div class="order-summary">
        <div class="summary-item">
          <span class="label">总金额:</span>
          <span class="value">¥{{ amount.toFixed(2) }}元</span>
        </div>
        <div class="summary-item">
          <span class="label">顾客姓名:</span>
          <span class="value">{{ customer?.name }}</span>
        </div>
        <div class="summary-item">
          <span class="label">押金:</span>
          <span class="value">¥{{ deposit.toFixed(2) }}元</span>
        </div>
        <div class="final-amount">
          <span class="label">最终应付金额:</span>
          <span class="value">¥{{ finalAmount.toFixed(2) }}</span>
        </div>
        <div class="amount-details">
          <div class="detail-item">原价: ¥{{ amount.toFixed(2) }}</div>
          <div class="detail-item">
            共优惠: ¥{{ discountAmount.toFixed(2) }}
          </div>
          <div class="detail-item">获得积分: {{ earnedPoints }}</div>
        </div>
      </div>

      <!-- 打折方式 -->
      <div class="discount-section">
        <h4>打折方式:</h4>
        <div class="discount-options">
          <div class="discount-option">
            <a-radio
              v-model:checked="discountType"
              value="member"
              @change="handleDiscountChange"
            >
              会员卡折扣 {{ customer?.memberCard }} 金卡(7折)
            </a-radio>
          </div>
          <div class="discount-option">
            <a-radio
              v-model:checked="discountType"
              value="whole"
              @change="handleDiscountChange"
            >
              整单折扣 {{ wholeOrderDiscount.toFixed(2) }}
            </a-radio>
          </div>
          <div class="discount-option">
            <a-radio
              v-model:checked="discountType"
              value="none"
              @change="handleDiscountChange"
            >
              不使用打折
            </a-radio>
          </div>
          <div class="manual-discount">
            <span class="label">手动改价:</span>
            <a-input-number
              v-model:value="manualDiscount"
              :precision="2"
              style="width: 120px"
              placeholder="0.00"
            />
            <span class="unit">元</span>
            <a-checkbox v-model:checked="roundOff">
              抹零: ¥{{ roundOffAmount.toFixed(2) }}
            </a-checkbox>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-section">
        <h4>选择支付方式</h4>
        <div class="payment-methods">
          <div class="payment-method">
            <a-checkbox v-model:checked="paymentMethods.alipay">
              支付宝
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.alipay"
              :precision="2"
              style="width: 120px"
              placeholder="0.00"
            />
          </div>
          <div class="payment-method">
            <a-checkbox v-model:checked="paymentMethods.wechat">
              微信
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.wechat"
              :precision="2"
              style="width: 120px"
              placeholder="0.00"
            />
          </div>
          <div class="payment-method">
            <a-checkbox v-model:checked="paymentMethods.cash">
              现金
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.cash"
              :precision="2"
              style="width: 120px"
              placeholder="0.00"
            />
          </div>
          <div class="payment-method">
            <a-checkbox v-model:checked="paymentMethods.card">
              银行卡
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.card"
              :precision="2"
              style="width: 120px"
              placeholder="0.00"
            />
          </div>
          <div class="payment-method">
            <a-checkbox v-model:checked="paymentMethods.deposit">
              押金
            </a-checkbox>
            <a-input-number
              v-model:value="paymentAmounts.deposit"
              :precision="2"
              style="width: 120px"
              placeholder="0.00"
            />
          </div>
        </div>

        <!-- 会员卡支付 -->
        <div class="member-card-payment">
          <div class="member-card-header">
            <a-checkbox v-model:checked="useMemberCard">
              会员卡支付: {{ customer?.memberCard }} 金卡
            </a-checkbox>
          </div>
          <div class="member-card-amounts">
            <div class="amount-item">
              <span class="label">余额支付:</span>
              <a-input-number
                v-model:value="memberCardPayment.balance"
                :precision="2"
                style="width: 120px"
                placeholder="0.00"
              />
            </div>
            <div class="amount-item">
              <span class="label">赠额支付:</span>
              <a-input-number
                v-model:value="memberCardPayment.gift"
                :precision="2"
                style="width: 120px"
                placeholder="0.00"
              />
            </div>
          </div>
          <div class="member-card-info">
            <span>余额: {{ customer?.balance.toFixed(2) }}</span>
            <span>赠额: 0.00</span>
          </div>
        </div>
      </div>

      <!-- 备注和操作 -->
      <div class="settlement-footer">
        <div class="remarks-section">
          <span class="label">备注:</span>
          <a-input
            v-model:value="remarks"
            placeholder="请输入备注信息"
            style="width: 200px"
          />
        </div>
        <div class="payment-total">
          <span class="label">支付合计:</span>
          <span class="value">¥{{ totalPayment.toFixed(2) }}元</span>
        </div>
        <div class="settlement-actions">
          <a-checkbox v-model:checked="autoPrint">
            结算自动完成打印
          </a-checkbox>
          <div class="action-buttons">
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" @click="handleConfirm"> 确认 </a-button>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.settlement-modal {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.order-summary {
  padding: 16px;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.summary-item .label {
  font-size: 14px;
  color: #666;
}

.summary-item .value {
  font-weight: bold;
  color: #333;
}

.final-amount {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin: 16px 0;
  background: #e6f7ff;
  border-radius: 4px;
}

.final-amount .label {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.final-amount .value {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
}

.amount-details {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.discount-section {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.discount-section h4 {
  margin: 0 0 16px;
  color: #333;
}

.discount-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.discount-option {
  display: flex;
  align-items: center;
}

.manual-discount {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 8px;
}

.manual-discount .label {
  font-size: 14px;
  color: #666;
}

.manual-discount .unit {
  font-size: 14px;
  color: #666;
}

.payment-section {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.payment-section h4 {
  margin: 0 0 16px;
  color: #333;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.payment-method {
  display: flex;
  gap: 12px;
  align-items: center;
}

.member-card-payment {
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.member-card-header {
  margin-bottom: 12px;
}

.member-card-amounts {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
}

.amount-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.amount-item .label {
  min-width: 60px;
  font-size: 14px;
  color: #666;
}

.member-card-info {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.settlement-footer {
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.remarks-section {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 16px;
}

.remarks-section .label {
  font-size: 14px;
  color: #666;
}

.payment-total {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 16px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
}

.payment-total .label {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.payment-total .value {
  font-size: 18px;
  font-weight: bold;
  color: #52c41a;
}

.settlement-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.action-buttons {
  display: flex;
  gap: 12px;
}
</style>
